package com.TheyChat.service.config.web;

import com.alibaba.fastjson.JSON;
import com.TheyChat.service.config.core.entity.ResponseMessage;
import com.TheyChat.service.config.core.entity.Result;
import com.TheyChat.service.config.core.entity.SpecialResponseMeta;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author: victor.w.ye
 * @Date: 2021/2/20 14:50
 * @Copyright:
 * @Company: luban
 * @Version: 1.0.0
 **/
@Configuration
@RestControllerAdvice(basePackages = "com.TheyChat")
public class JsonResultResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return Result.success();
        }
        else if (body instanceof ResponseMessage){
            return body;
        }
        //处理返回值是String的情况
        if (body instanceof String) {
            return body.toString();
        }
        if (body instanceof Exception) {
            return JSON.toJSONString(((Exception) body).getMessage());
        }
        if (body instanceof SpecialResponseMeta) {
            return body;
        }
        if (body instanceof byte[]) {
            return body;
        }
        return Result.success(body);
    }


}
